package com.kongchengji.zhanguafou.quartz;

import com.kongchengji.zhanguafou.constant.WxInfo;
import com.kongchengji.zhanguafou.dao.QuartzDAO;
import com.kongchengji.zhanguafou.domain.QuartzDO;
import com.kongchengji.zhanguafou.utils.FormatTimeUtil;
import com.kongchengji.zhanguafou.utils.PingServerUtil;
import okhttp3.*;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import java.io.IOException;
import java.io.Serializable;
import java.util.Map;

@Component // 此注解必加
@EnableScheduling // 此注解必加
public class ListenServerScheduleTask implements Job,Serializable {
    @Autowired
    private QuartzDAO quartzDAO;
    private QuartzDO quartzDO;
    private  String message;
    private  String level;
    private  String ipAddress;

    @Override
    public void execute(JobExecutionContext context){
        try {
            //获取传递过来的quartz对象
            JobDataMap dataMap = context.getJobDetail().getJobDataMap();
            QuartzDO quartz = (QuartzDO) dataMap.get("quartz");
            ipAddress = quartz.getUrl();
            String openId = quartz.getOpenId();
            String jobName = quartz.getJobName();
            //通过任务的唯一标识得到是否是第一次发送信息
            Example example = new Example(QuartzDO.class);
            example.createCriteria().andEqualTo("jobName",jobName);
            quartzDO = quartzDAO.selectOneByExample(example);
            //得到服务器是否连通标识,为false则发送警告信息。
            boolean isConnect = getConnectFlag();
            if (!isConnect) {
                sendMessage(openId);
            }
            //为true同时不是第一次发送恢复通知
            if(isConnect && quartzDO.getFirst() == 0){
                sendMessage(openId);
            }
        }
        catch(Exception e) {
            //防止抛出未知异常导致任务结束
            e.printStackTrace();
        }

    }
    /**
     * 将消息发送给用户
     * @param openId 用户id
     */
    private void sendMessage(String openId)  {
        String json = buildMessage(openId);
        RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8")
                , json);
        Request request = new Request.Builder()
                .url("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+ WxInfo.accessToken.getToken())//请求的url
                .post(requestBody)
                .build();
        OkHttpClient client = new OkHttpClient();
        try {
            client.newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



    /**
     * 构造返回消息模板
     * @param openId 用户id
     * @return 返回构造好的消息
     */
    private String buildMessage(String openId) {
        String json;
        //判读是否是第一次发送
        if (quartzDO.getFirst() == 1) {//第一次发送宕机通知模板
            //修改数据库中该任务的first为0
            quartzDO.setFirst(0);
            quartzDAO.updateByPrimaryKey(quartzDO);
            json = "{" +
                    "           \"touser\":\"" + openId + "\"," +
                    "           \"template_id\":\"r9lxpEEy755T-6Xx769UKO-Aawr3V-w5CDufgW9SBiA\"," +
                    "           \"data\":{" +
                    "                   \"first\": {" +
                    "                       \"value\":\""+message+"\"," +
                    "                       \"color\":\"#FF0000\"" +
                    "                   }," +
                    "                   \"keyword1\":{" +
                    "                       \"value\":\"" + FormatTimeUtil.getFormatTime() + "\"," +
                    "                       \"color\":\"#173177\"" +
                    "                   }," +
                    "                   \"keyword2\": {" +
                    "                       \"value\":\""+level+"\"," +
                    "                       \"color\":\"#173177\"" +
                    "                   }," +
                    "                   \"keyword3\":{" +
                    "                       \"value\":\""+ipAddress+"\"," +
                    "                       \"color\":\"#173177\"" +
                    "                   }," +
                    "                   \"remark\": {" +
                    "                       \"value\":\"请及时处理\"," +
                    "                       \"color\":\"#173177\"" +
                    "                   }" +
                    "           }" +
                    "       }";
        } else {//不是第一次发送恢复通知模板
            //修改first字段为 1
            quartzDO.setFirst(1);
            quartzDAO.updateByPrimaryKey(quartzDO);
            json = "{" +
                    "           \"touser\":\"" + openId + "\"," +
                    "           \"template_id\":\"OvBfi43054FtahoVfHVLtvjh4vdsawzPtFdhFYqpMO0\"," +
                    "           \"data\":{" +
                    "                   \"first\": {" +
                    "                       \"value\":\"你的服务器"+quartzDO.getName()+"已经恢复正常\"," +
                    "                       \"color\":\"#FF0000\"" +
                    "                   }," +
                    "                   \"keyword1\":{" +
                    "                       \"value\":\"可能是网络原因\"," +
                    "                       \"color\":\"#173177\"" +
                    "                   }," +
                    "                   \"keyword2\": {" +
                    "                       \"value\":\""+ FormatTimeUtil.getFormatTime()+"\"," +
                    "                       \"color\":\"#173177\"" +
                    "                   }," +
                    "                   \"remark\":{" +
                    "                       \"value\":\"站挂否持续为你服务\"," +
                    "                       \"color\":\"#173177\"" +
                    "                   }" +
                    "           }" +
                    "       }";
        }
        return json;
    }



    /**
     * 根据ping返回的结果返回服务器是否连通标识
     * @return 返回结果
     */
    private boolean getConnectFlag(){
        Map<String,String> map = PingServerUtil.pingServer(ipAddress);
        //如果time为空,则一定是服务器无法连通,返回true.
        if(map.get("time") == null){
            message = "你的服务器无法连接";
            level = "严重警告";
            return false;
        }
        return true;
    }


}
